import 'dart:async';
import 'package:dio/dio.dart';
import 'package:honeypotflutter/net/public_httpInterceptor.dart';
import 'package:honeypotflutter/net/public_httpInfo.dart';
import 'package:honeypotflutter/net/public_httpResult.dart';
import 'package:honeypotflutter/public/public_total.dart';

class MGHttp {
  static final MGHttp _instance = MGHttp._internal();

  /*
  * 请求dio
  * */
  late Dio _dio;

  /*
  * 初始化数据
  * */
  MGHttp._internal() {
    BaseOptions option = BaseOptions(
      baseUrl: MGHttpInfo.sysUrl,
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 20),
      contentType: "application/json;Charset=UTF-8",
      responseType: ResponseType.json,
    );
    _dio = Dio(option);
    _dio.interceptors.add(HttpInterceptor());
  }

  /*
  * 单例
  * */
  static MGHttp instance() {
    return _instance;
  }

  /*
  * 设置url
  * */
  static setBaseUrl(String url) {
    if (url.isEmpty) {
      return;
    }
    MGHttp.instance()._dio.options.baseUrl = url;
  }

  /*
  * get请求
  * */
  static Future<R?> get<R>(String path, {Map<String, dynamic>? params, String? progress}) async {
    return _request<R>(path, queryParameters: params, method: "GET", progress: progress);
  }

  /*
  * post请求
  * */
  static Future<R?> post<R>(String path, {Object? params, String? progress}) async {
    return _request<R>(path, data: params, method: "POST", progress: progress);
  }

  /*
  * delete请求
  * */
  static Future<R?> delete<R>(String path, {Map<String, dynamic>? params, String? progress}) async {
    return _request<R>(path, queryParameters: params, method: "DELETE", progress: progress);
  }

  /*
  * put请求
  * */
  static Future<R?> put<R>(String path, {Object? params, String? progress}) async {
    return _request<R>(path, data: params, method: "PUT", progress: progress);
  }

  /*
  * 公共网络请求
  * */
  static Future<R?> _request<R>(String path, {Map<String, dynamic>? queryParameters, Object? data, String method = "POST", String? progress}) async {
    if (progress != null) {
      HLTotal.progress(status: progress);
    }
    try {
      Options options = Options(method: method);
      var result = await MGHttp.instance()._dio.request<HttpResult>(path, queryParameters: queryParameters, data: data, options: options);
      if (result.data == null) {
        return null;
      }
      if (result.data!.success) {
        return result.data!.result as R;
      } else {
        return Future.error(result.data?.error as Object);
      }
    } on DioException catch (error) {
      HttpErrorResult err = error.error as HttpErrorResult;
      return Future.error(err);
    } finally {
      if (progress != null) {
        HLTotal.dismiss();
      }
    }
  }
}
